<template>
  <a-modal
    centered
    :title="name + '选择'"
    :width='width'
    :visible='visible'
    switchFullscreen
    @ok='handleOk'
    @cancel='close'
    cancelText='关闭'>

    <a-row :gutter='18'>
      <a-col :span='multiple?16:24'>
        <!-- 查询区域 -->
        <a-form layout='inline' class='j-inline-form'>
          <!-- 固定条件 -->
          <j-select-biz-query-item v-if='queryConfig.length>0' v-show='showMoreQueryItems' :queryParam='queryParam'
                                   :queryConfig='queryConfig' @pressEnter='searchQuery' />
          <a-form-item>
            <a-input v-model='queryParam[queryParamCode||valueKey]' :placeholder='(queryParamText||name)'
                     @pressEnter='searchQuery' />
          </a-form-item>
          <!-- 动态生成的查询条件 -->
          <!-- 按钮 -->
          <a-button type='primary' @click='searchQuery' icon='search'>查询</a-button>
          <a-button type='primary' @click='searchReset' icon='reload' style='margin-left: 4px;marginBottom:8px'>重置
          </a-button>
          <a v-if='queryConfig.length>0' @click='showMoreQueryItems=!showMoreQueryItems' style='margin-left: 4px'>
            {{ showMoreQueryItems ? '收起' : '展开' }}
            <a-icon :type="showMoreQueryItems ? 'up' : 'down'" />
          </a>
        </a-form>

        <vxe-grid
          ref='xGrid'
          :border='true'
          :resizable='true'
          :showOverflow='true'
          size='mini'
          :row-id='rowKey'
          :loading='loading'
          :height=300
          :align='left'
          :columns='innerColumns'
          :data='dataSource'
          :row-config='{ isCurrent: true, keyField: rowKey }'
          :checkbox-config="{ trigger: 'row',checkRowKeys: selectedRowKeys, reserve: true}"
          :radio-config="{ trigger: 'row',checkRowKeys: selectedRowKeys,reserve: true}"
          @checkbox-change='selectChangeEvent'
          @checkbox-all='selectChangeEvent'
          @cell-dblclick='selectDblclick'
        >
          <template #pager>
            <vxe-pager
              :layouts="['Total', 'PrevJump', 'PrevPage', 'Number', 'NextPage', 'NextJump','Sizes', 'FullJump']"
              :currentPage.sync='ipagination.current'
              :page-size.sync='ipagination.pageSize'
              :total='ipagination.total'
              :pageSizes='ipagination.pageSizeOptions'
              @page-change='handlePageChange'>
            </vxe-pager>
          </template>
        </vxe-grid>
      </a-col>
      <a-col :span='multiple?8:0'>
        <div class='selected_title'> 已选{{ name }}</div>
        <vxe-grid
          ref='xGrid1'
          :border='true'
          :resizable='true'
          :showOverflow='true'
          size='mini'
          :row-id='rowKey'
          :loading='loading'
          :height=300
          :align='left'
          :data='selectedTable.dataSource'
          :columns='selectedTable.columns'
        >
          <template #action='{ row:record ,rowIndex:index}'>
            <a @click='handleDeleteSelected(record, index)'>删除</a>
          </template>
        </vxe-grid>
      </a-col>
    </a-row>
  </a-modal>
</template>

<script>
import JTreeSelect from '@/components/cn-form/JTreeSelect'
import { filterObj } from '@/utils/util'
import { getAction, postAction } from '@/api/manage'
import Ellipsis from '@/components/ellipsis'
import { PageListMixin } from '@/mixins/PageListMixin'
import { cloneObject, pushIfNotExist } from '@/utils/util'
import JSelectBizQueryItem from './JSelectBizQueryItem'

export default {
  name: 'JSelectBizComponentModal',
  mixins: [PageListMixin],
  components: { Ellipsis, JSelectBizQueryItem, JTreeSelect },
  props: {
    roleCodes: {
      type: String,
      default: undefined
    },
    value: {
      type: Array,
      default: () => []
    },
    visible: {
      type: Boolean,
      default: false
    },
    valueKey: {
      type: String,
      required: true
    },
    multiple: {
      type: Boolean,
      default: true
    },
    width: {
      type: Number,
      default: 900
    },
    name: {
      type: String,
      default: ''
    },
    listUrl: {
      type: String,
      required: true,
      default: ''
    },
    // 根据 value 获取显示文本的地址，例如存的是 username，可以通过该地址获取到 realname
    valueUrl: {
      type: String,
      default: ''
    },
    displayKey: {
      type: String,
      default: null
    },
    columns: {
      type: Array,
      required: true,
      default: () => []
    },
    // 查询条件Code
    queryParamCode: {
      type: String,
      default: null
    },
    // 查询条件文字
    queryParamText: {
      type: String,
      default: null
    },
    // 查询配置
    queryConfig: {
      type: Array,
      default: () => []
    },
    // 查询配置
    queryParams: {
      type: Object,
      default: () => {
      }
    },
    rowKey: {
      type: String,
      default: 'id'
    },
    returnName: {
      type: Boolean,
      default: false
    },
    // 过长裁剪长度，设置为 -1 代表不裁剪
    ellipsisLength: {
      type: Number,
      default: 12
    }
  },

  data() {
    return {
      innerValue: [],
      // 已选择列表
      selectedTable: {
        columns: [
          { type: 'seq', width: 50, title: '编号', fixed: 'left' },
          {
            title: this.columns[0].title,
            field: this.columns[0].field,
          },
          { title: '操作', field: 'action', align: 'center', width: 60, slots: { default: 'action' } }
        ],
        dataSource: []
      },
      renderEllipsis: (value) => (<ellipsis length={this.ellipsisLength}>{value}</ellipsis>),
      url: { list: this.listUrl },
      /* 分页参数 */
      ipagination: {
        current: 1,
        pageSize: 5,
        pageSizeOptions: [5, 10, 20, 30],
        showTotal: (total, range) => {
          return range[0] + '-' + range[1] + ' 共' + total + '条'
        },
        showQuickJumper: true,
        showSizeChanger: true,
        total: 0
      },
      options: [],
      dataSourceMap: {},
      showMoreQueryItems: true
    }
  },
  computed: {
    // 表头
    innerColumns() {
      let columns = cloneObject(this.columns)
      columns.unshift({ type: this.multiple ? 'checkbox' : 'radio', width: 60, fixed: 'left' })
      columns.forEach(column => {
        // 给所有的列加上过长裁剪
        if (this.ellipsisLength !== -1) {
          column.customRender = (text) => this.renderEllipsis(text)
        }
      })
      return columns
    }
  },
  watch: {
    value: {
      deep: true,
      immediate: true,
      handler(val) {
        this.innerValue = cloneObject(val)
        this.selectedRowKeys = []
        this.valueWatchHandler(val)
        this.queryOptionsByValue(val)
      }
    },
    dataSource: {
      deep: true,
      handler(val) {
        this.emitOptions(val)
        this.valueWatchHandler(this.innerValue)
      }
    },
    selectedRowKeys: {
      immediate: true,
      deep: true,
      handler(val) {
        //update--begin--autor:scott-----date:20200927------for：选取职务名称出现全选 #1753-----
        if (this.innerValue) {
          this.innerValue.length = 0
        }
        console.log(val)
        //update--end--autor:scott-----date:20200927------for：选取职务名称出现全选 #1753-----
        let dataSource = val.map(key => {
          for (let data of this.dataSource) {
            if (data[this.rowKey] === key) {
              pushIfNotExist(this.innerValue, data[this.valueKey])
              return data
            }
          }
          for (let data of this.selectedTable.dataSource) {
            if (data[this.rowKey] === key) {
              pushIfNotExist(this.innerValue, data[this.valueKey])
              return data
            }
          }
          console.warn('未找到选择的行信息，key：' + key)
          return {}
        })
        // debugger
        // this.selectedTable.dataSource = dataSource
      }
    },
    roleCodes: {
      deep: true,
      immediate: true,
      handler(val) {
        if (val) {
          let codes = val.split(',')
          this.selectedTable.dataSource = codes.map((item, index) => {
            let obj = {
              roleName: this.value[index],
              roleCode: item
            }
            this.dataSourceMap[this.value[index]] = obj
            return obj
          })
        }
      }
    }
  },

  methods: {
    handleTableChange(pagination, filters, sorter) {
      //分页、排序、筛选变化时触发
      //TODO 筛选
      if (Object.keys(sorter).length > 0) {
        this.isorter.column = sorter.field
        this.isorter.order = 'ascend' == sorter.order ? 'asc' : 'desc'
      }
      this.ipagination = pagination
      this.loadData()
    },
    getQueryParams() {
      //获取查询条件
      let sqp = {}
      if (this.superQueryParams) {
        sqp['superQueryParams'] = encodeURI(this.superQueryParams)
        sqp['superQueryMatchType'] = this.superQueryMatchType
      }
      var param = Object.assign(sqp, this.queryParam, this.isorter, this.filters, this.searchOn, this.queryParams)
      param.field = this.getQueryField()
      param.current = this.ipagination.current
      param.size = this.ipagination.pageSize
      return filterObj(param)
    },

    /** 关闭弹窗 */
    close() {
      this.$emit('update:visible', false)
    },

    valueWatchHandler(val) {
      val.forEach(item => {
        this.dataSource.concat(this.selectedTable.dataSource).forEach(data => {
          if (data[this.valueKey] === item) {
            pushIfNotExist(this.selectedRowKeys, data[this.rowKey])
          }
        })
      })
    },

    queryOptionsByValue(value) {
      if (this.roleCodes) {
        let codes = this.roleCodes.split(',')
        this.$set(this, 'selectedRowKeys', codes)
        this.roleCodes == ' '
        console.log(this.selectedRowKeys)
      }
      if (!value || value.length === 0) {
        return
      }
      // 判断options是否存在value，如果已存在数据就不再请求后台了
      let notExist = false
      for (let val of value) {
        let find = false
        for (let option of this.options) {
          if (val === option.value) {
            find = true
            break
          }
        }
        if (!find) {
          notExist = true
          break
        }
      }

      if (!notExist) return
      postAction(this.valueUrl || this.listUrl, {
        // 这里最后加一个 , 的原因是因为无论如何都要使用 in 查询，防止后台进行了模糊匹配，导致查询结果不准确
        [this.valueKey]: value.join(',') ,
        pageNo: 1,
        pageSize: value.length
      }).then((res) => {
        if (res.success) {
          let dataSource = res.result
          if (!(dataSource instanceof Array)) {
            dataSource = res.result.records
          }
          this.emitOptions(dataSource, (data) => {
            pushIfNotExist(this.innerValue, data[this.valueKey])
            pushIfNotExist(this.selectedRowKeys, data[this.rowKey])
            pushIfNotExist(this.selectedTable.dataSource, data, this.rowKey)
          })
          const $grid = this.$refs.xGrid
          if (this.multiple) {
            $grid && $grid.setCheckboxRow(this.selectedTable.dataSource, true)
          } else {
            $grid && $grid.setRadioRow(this.selectedTable.dataSource[0]||{})
            console.log(this.selectedTable.dataSource[0])
          }
        }

      })

    },
    emitOptions(dataSource, callback) {
      this.selectedTable.dataSource.concat(dataSource).forEach(data => {
        let key = data[this.valueKey]
        this.dataSourceMap[key] = data
        pushIfNotExist(this.options, { label: data[this.displayKey || this.valueKey], value: key }, 'value')
        typeof callback === 'function' ? callback(data) : ''
      })
      this.$emit('options', this.options, this.dataSourceMap)
    },

    selectDblclick({row}){
      if(!this.multiple){
        let value = [row[this.valueKey]]
        this.$emit('input', value, this.selectedTable.dataSource)
        this.close()
      }
    },

    /** 完成选择 */
    handleOk() {
      let value = this.selectedTable.dataSource.map(data => data[this.valueKey])
      this.$emit('input', value, this.selectedTable.dataSource)
      this.close()
    },
    /** 删除已选择的 */
    handleDeleteSelected(record, index) {
      const $grid = this.$refs.xGrid
      if (this.multiple) {
        $grid && $grid.setCheckboxRow([record], false)
      } else {
        $grid && $grid.clearRadioReserve()
        $grid && $grid.clearRadioRow()
      }
      this.selectedRowKeys.splice(this.selectedRowKeys.indexOf(record[this.rowKey]), 1)
      //update--begin--autor:wangshuai-----date:20200722------for：JSelectBizComponent组件切换页数值问题------
      let selectIndex = this.selectedTable.dataSource.findIndex(v => v[this.valueKey] == record[this.valueKey])
      selectIndex != -1 && this.selectedTable.dataSource.splice(selectIndex, 1)
      this.innerValue.splice(this.innerValue.indexOf(record[this.valueKey]), 1)
      console.log('this.selectedRowKeys:', this.selectedRowKeys)
      console.log('this.selectedTable.dataSource:', this.selectedTable.dataSource)
      //update--begin--autor:wangshuai-----date:20200722------for：JSelectBizComponent组件切换页数值问题------
    },

    // vxe表格多选
    selectChangeEvent({ records }) {
      const $grid = this.$refs.xGrid
      const reserves = $grid && $grid.getCheckboxReserveRecords()
      const result = reserves.concat(records)
      console.log(this.rowKey)
      if (this.multiple) {
        this.selectedTable.dataSource = result
        this.selectedRowKeys = result.map(item => item[this.rowKey])
      } else {
        let results = []
        if (this.selectedTable.dataSource.length && this.selectedTable.dataSource[0][this.rowKey]) {
          results = result.filter((obj, index) => {
            return obj[this.rowKey] !== this.selectedTable.dataSource[0][this.rowKey]
          })
        } else {
          results = result
        }

        $grid && $grid.clearCheckboxReserve()
        $grid && $grid.clearCheckboxRow()
        if (results.length == 1) {
          this.selectedTable.dataSource = [results[0]]
          this.selectedRowKeys = [results[0][this.rowKey]]
        } else {
          $grid && $grid.clearRadioReserve()
          $grid && $grid.clearRadioRow()
          this.selectedTable.dataSource = []
          this.selectedRowKeys = []
        }

      }
    }
  }
}
</script>
<style lang='less' scoped>
.selected_title {
  height: 36px;
  line-height: 36px;
  font-size: 14px;
  font-weight: 500;
}

.full-form-item {
  display: flex;
  margin-right: 0;

  /deep/ .ant-form-item-control-wrapper {
    flex: 1 1;
    display: inline-block;
  }
}

.j-inline-form {
  /deep/ .ant-form-item {
    margin-bottom: 12px;
  }

  /deep/ .ant-form-item-label {
    line-height: 32px;
    width: auto;
  }

  /deep/ .ant-form-item-control {
    height: 32px;
    line-height: 32px;
  }
}

</style>
